import React from 'react';
import { connect } from 'dva';
import { Upload, Icon, message } from 'antd';

function getBase64(img, callback) {
	const reader = new FileReader();
	reader.addEventListener('load', () => callback(reader.result));
	reader.readAsDataURL(img);
}

function beforeUpload(file) {
	const isJPG = file.type === 'image/jpeg';
	if (!isJPG) {
		message.error('You can only upload JPG file!');
	}
	const isLt2M = file.size / 1024 / 1024 < 2;
	if (!isLt2M) {
		message.error('Image must smaller than 2MB!');
	}
	return isJPG && isLt2M;
}

class UploadPage extends React.Component {
	state = {
		UploadLoading: false
	};

	handleChange = (info) => {
		const { dispatch, UploadLoading } = this.props;
		if (info.file.status === 'uploading') {
			dispatch({
				type: 'indexpage/setState',
				payload: {
					UploadLoading: true
				}
			});

			return;
		}
		if (info.file.status === 'done') {
			// Get this url from response in real world.
			getBase64(info.file.originFileObj, (imageUrl) =>
				dispatch({
					type: 'indexpage/setState',
					payload: {
						imageUrl,
						UploadLoading: false
					}
				})
			);
		}
	};

	saveimg = () => {
		const { dispatch, imageUrl, username } = this.props;
		dispatch({
			type: 'indexpage/upload',
			payload: {
				username: username,
				imageUrl: imageUrl
			}
		});
	};

	render() {
		const { dispatch, UploadLoading, imageUrl, avater } = this.props;
		console.log(imageUrl);
		const uploadButton = (
			<div>
				<Icon type={UploadLoading ? 'loading' : 'plus'} />
				<div className="ant-upload-text">Upload</div>
			</div>
		);

		return (
			<div>
				<Upload
					name="avatar"
					listType="picture-card"
					className="avatar-uploader"
					showUploadList={false}
					action="//jsonplaceholder.typicode.com/posts/"
					beforeUpload={beforeUpload}
					onChange={this.handleChange}
				>
						{imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}	
				</Upload>
				<button onClick={this.saveimg}>保存</button>
			</div>
		);
	}
}

export default connect(({ indexpage }) => ({ ...indexpage }))(UploadPage);
